package com.atguigu.process.service.impl;


import com.atguigu.model.process.ProcessTemplate;
import com.atguigu.model.process.ProcessType;
import com.atguigu.process.mapper.OaProcessTemplateMapper;
import com.atguigu.process.service.OaProcessTemplateService;
import com.atguigu.process.service.OaProcessTypeService;
import com.atguigu.process.service.ProcessService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 * 审批模板 服务实现类
 * </p>
 *
 * @author ws
 * @since 2024-01-16
 */
@Service
public class OaProcessTemplateServiceImpl extends ServiceImpl<OaProcessTemplateMapper, ProcessTemplate> implements OaProcessTemplateService {

    @Resource
    private OaProcessTypeService oaProcessTypeService;

    @Resource
    private ProcessService processService;

    @Override
    public Page<ProcessTemplate> selectPage(Page<ProcessTemplate> pageParam) {
        //1.调用mapper的方法实现分页查询
        Page<ProcessTemplate> processTemplatePage = baseMapper.selectPage(pageParam,null);
        //2.第一步分页查询返回分页数据，从分页而数据获取列表list集合
        List<ProcessTemplate> records = processTemplatePage.getRecords();
        //3.遍历list集合，得到每个对象的审批id
        for (ProcessTemplate record : records) {
            //4.根据审批类型id，查询获取对应名称
            Long processTypeId = record.getProcessTypeId();
            LambdaQueryWrapper<ProcessType> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(ProcessType::getId,processTypeId);
            ProcessType one = oaProcessTypeService.getOne(wrapper);
            if(ObjectUtils.isEmpty(one)){
                continue;
            }
            //完成最终封装，processTypeName
            record.setProcessTypeName(one.getName());
        }
        return processTemplatePage;
    }

    /**
     * 发布模板
     * @param id
     */
    @Override
    public void publish(Long id) {
        //修改模板发布状态 1.已经发布
        ProcessTemplate processTemplate = baseMapper.selectById(id);
        processTemplate.setStatus(1);
        baseMapper.updateById(processTemplate);
        //TODO 后续完善，流程定义部署
        if(!StringUtils.isEmpty(processTemplate.getProcessDefinitionPath())){
             processService.deployByZip(processTemplate.getProcessDefinitionPath());
        }

    }
}
